package com.itmuch.box.service.config;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.itmuch.box.core.base.BaseService;
import com.itmuch.box.dao.config.ConfigRepository;
import com.itmuch.box.domain.config.Config;

@Service
@Transactional
@CacheConfig(cacheNames = "config")
public class ConfigService extends BaseService<ConfigRepository, Config> {

    // TODO 加入缓存
    public Map<String, String> genMap(List<Config> list) {
        Map<String, String> map = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(list)) {
            for (Config config : list) {
                map.put(config.getK(), config.getV());
            }
        }
        return map;
    }

    public List<Config> findByModuleAndName(String module, String name) {
        return this.dao.findByModuleAndName(module, name);
    }

    public Map<String, String> findByModuleAndName4Map(String module, String name) {
        return this.genMap(this.findByModuleAndName(module, name));
    }

    private Map<String, String> findAll4StringMap() {
        return this.genMap(this.findAll());
    }

    @Override
    public List<Config> findAll() {
        return super.findAll();
    }

    public String selectValueByKey(String key) {
        return this.findAll4StringMap().get(key);
    }

    @Cacheable
    public Config findByModuleAndK(String module, String key) {
        return this.dao.findByModuleAndK(module, key);
    }

}
